package com.gxa.common;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

public class CustomizedModularRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

        this.assertRealmsConfigured();

        CustomizedToken token = (CustomizedToken) authenticationToken;

        String LoginType = token.getLoginType();

        Collection<Realm> realms = this.getRealms();

        System.out.println(realms);

        Collection<Realm> typeRealms = new ArrayList<>();

        for (Realm realm :realms){
            if (realm.getName().contains(LoginType)){
                typeRealms.add(realm);
            }
        }
        if (typeRealms.size() == 1) {
            return this.doSingleRealmAuthentication(typeRealms.iterator().next(),token);
        }else {
            return  this.doMultiRealmAuthentication(typeRealms,token);
        }

    }
}
